/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lucene;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;

/**
 *
 * @author Putra
 */
public class GetXMLComponent {

    private File fXmlFile;
    private DocumentBuilderFactory dbFactory;
    private DocumentBuilder dBuilder;
    private Document doc;

    public GetXMLComponent(String path) {
        try {
            fXmlFile = new File(path);
            dbFactory = DocumentBuilderFactory.newInstance();
            dBuilder = dbFactory.newDocumentBuilder();
            doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private boolean titleCompare(String a, String b){
        String[] aa=a.split(" ");
        String[] bb=b.split(" ");
        int count=0;
        for(String temp:aa){
            for(String temp2:bb){
                if(temp.equals(temp2)){
                    count++;
                    break;
                }
            }
        }
        if(count>=2) return true;
        else return false;
    }
    
    public Element getElementPhoneByTitle(String majorTag, String title) {
        NodeList nList = doc.getElementsByTagName(majorTag);
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                String ss = eElement.getElementsByTagName("title").item(0).getNodeValue();
                if(titleCompare(ss,title)){
                    return eElement;
                }
            }
        }
        return null;
    }
}
